﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;

namespace VSA.Applications
{
    /// <summary>
    /// 用于生成Excel文件的类
    /// </summary>
    public class ExcelFile
    {
        private DataTable tbExcel = null;
        /// <summary>
        /// 默认构造函数！
        /// </summary>
        public ExcelFile()
        {
        }
        /// <summary>
        /// 默认构造函数！
        /// </summary>
        public ExcelFile(DataTable tbData)
        {
            this.tbExcel = tbData;
        }
        /// <summary>
        /// 设置生成的Excel文件中的数据源
        /// </summary>
        public DataTable ExcelDataTable
        {
            set
            {
                this.tbExcel = value;
            }
        }
        /// <summary>
        /// 把数据表导出到Excel文件
        /// </summary>
        /// <param >文件路径</param>
        /// <returns></returns>
        public bool Create(string FilePath)
        {
            FilePath = FilePath.Trim();
            if (FilePath.Length == 0)
            {
                throw new Exception("对不起，文件名不能为空！");
            }
            if (!FilePath.ToUpper().EndsWith(".XLS"))
            {
                FilePath += ".xls";
            }
            using (StreamWriter writer = new StreamWriter(FilePath, false, Encoding.GetEncoding("gb2312")))
            {
                string s = "";
                foreach (DataColumn col in this.tbExcel.Columns)
                {
                    s += col.ColumnName + "\t";
                }
                writer.WriteLine(s);
                foreach (DataRow row in this.tbExcel.Rows)
                {
                    s = "";
                    for (int i = 0; i < this.tbExcel.Columns.Count; i++)
                    {
                        s += row[i].ToString().Trim() + "\t";
                    }
                    writer.WriteLine(s);
                }
                //writer.Flush();
                writer.Close();
            }
            return true;
        }
    }
}
